/**
 * 微信服务类
 * 解决一些公共接口的调用
 */
const axios = require('axios');
const { getRedisValue, setRedisValue } = require('../../db/redis')

const accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential';
const jscode2Session = 'https://api.weixin.qq.com/sns/jscode2session';
const WXaCodeUrl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit';

const appidSecretMap = {
    'wx30a80601a7fa41c0': '40d10840a559b1f8423cb1b264505af9', // 【MasterH Wallpaper】小程序
    'wxafd8ec7535068dba': 'e179c65b4fd7ebe4593af9ac930f08fa', // 【MasterH杂货铺】公众号
    'wx120ad1f3794856de': '5c9a0e7e8a5a6657a532261257307e7d', // 被封的【黄师傅AI聊天】小程序
}
/**
 * 通过appid和appSecret获取accessToken，并存储到redis，有效期1小时50分钟
 * 由于不止一个小程序或公众号，所以appid由外面传进来
 */
exports.getAccessTokenWX = async (appid) => {
    return new Promise((resolve, reject) => 
        axios.get(accessTokenUrl + '&appid=' + appid + '&secret=' + appidSecretMap[appid]).then((res) => {
            const dataObj = res.data;
            setRedisValue(appid, dataObj.access_token, 7100);
            resolve(dataObj.access_token);
        }).catch((err) => {
            reject(err);
        })
    );
}

/**
 * 通过appid，code获取微信用户openid
 * @param {*} code 
 * @returns 
 */
exports.getWXUserInfoByCode = async (appid, code) => {
    const res = await getUserInfo(appid, code);
    if (res.openid) {
        return {
            flag: 1,
            msg: 'success',
            data: {
                openId: res.openid,
            }
        }
    } else {
        return {
            flag: res.errcode,
            msg: res.errmsg
        }
    }
}

/**
 * 调用微信jscode2session接口
 * @param {*} appid 
 * @param {*} code 
 * @returns 
 */
const getUserInfo = async (appid, code) => {
    let accessToken = await getRedisValue(appid);
    if (!accessToken) {
        accessToken = await this.getAccessTokenWX(appid);
    }
    const res = await new Promise((resolve, reject) => {
        axios.get(jscode2Session + '?appid=' + appid + '&secret=' + appidSecretMap[appid] + '&js_code=' + code + '&grant_type=authorization_code').
        then((res) => {
            resolve(res.data);
        }).catch((err) => {
            reject(err);
        })
    });
    return res;
}